package com.tmpt.security;

import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class MyAccessDecisionManager implements AccessDecisionManager {

	public void decide(Authentication authentication, Object object,
					   Collection<ConfigAttribute> configAttrList) throws AccessDeniedException,
			InsufficientAuthenticationException {

		/*UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
		System.out.println("==ddd===========:"+userDetails.getUsername());
		*/

		if(configAttrList==null || configAttrList.size()==0){
			//字不能修改，要和condition.jsp对应
			throw new AccessDeniedException("资源权限未分配");
		}

		Iterator<ConfigAttribute> iterator = configAttrList.iterator();
		while(iterator.hasNext()){
			ConfigAttribute configAttr = iterator.next();
			String needPermision = configAttr.getAttribute();
			System.out.println("needPermision:"+needPermision);
			for(GrantedAuthority myAuth: authentication.getAuthorities()){
				//放行的URL
				if(needPermision.equals("_ACCESS")){
					return;
				}
				//System.out.println("myAuth.getAuthority():"+myAuth.getAuthority());
				if(needPermision.equals(myAuth.getAuthority())){
					return;
				}
			}
		}

		System.out.println("没有权限访问！");
		throw new AccessDeniedException("没有权限访问！");
	}

	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}

}
